#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/9/23'
"""
# encoding: UTF-8


import requests
import time
HTTP_OK = 200

PERIOD_1MIN = '1m'
PERIOD_5MIN = '5m'
PERIOD_15MIN = '15m'
PERIOD_60MIN = '60m'
PERIOD_1DAY = '1d'


########################################################################
class ShcifcoApi(object):
    """数据接口"""

    # ----------------------------------------------------------------------
    def __init__(self, ip, port, token):
        """Constructor"""
        self.ip = ip
        self.port = port
        self.token = token

        self.service = 'shcifco/dataapi'
        self.domain = 'http://' + ':'.join([self.ip, self.port])

    # ----------------------------------------------------------------------
    def getData(self, path, params):
        """下载数据"""
        url = '/'.join([self.domain, self.service, path])
        params['token'] = self.token
        r = requests.get(url=url, params=params)

        if r.status_code != HTTP_OK:
            print
            u'http请求失败，状态代码%s' % r.status_code
            return None
        else:
            return r.text

    # ----------------------------------------------------------------------
    def getLastTick(self, symbol):
        """获取最新Tick"""
        path = 'lasttick'
        params = {'ids': symbol}

        data = self.getData(path, params)
        if not data or data == ';':
            return None

        data = data.split(';')[0]
        l = data.split(',')
        d = {
            'symbol': l[0],
            'lastPrice': float(l[1]),
            'bidPrice': float(l[2]),
            'bidVolume': int(l[3]),
            'askPrice': float(l[4]),
            'askVolume': int(l[5]),
            'volume': int(l[6]),
            'openInterest': int(float(l[7]))
        }
        return d

    # ----------------------------------------------------------------------
    def getLastPrice(self, symbol):
        """获取最新成交价"""
        path = 'lastprice'
        params = {'ids': symbol}

        data = self.getData(path, params)
        if not data:
            return None

        data = data.split(';')[0]
        price = float(data)
        return price

    # ----------------------------------------------------------------------
    def getLastBar(self, symbol):
        """获取最新的一分钟K线数据"""
        path = 'lastbar'
        params = {'id': symbol}

        data = self.getData(path, params)
        if not data:
            return None

        data = data.split(';')[0]
        l = data.split(',')
        d = {
            'symbol': l[0],
            'time': l[1],
            'open': float(l[2]),
            'high': float(l[3]),
            'low': float(l[4]),
            'close': float(l[5]),
            'volume': int(l[6]),
            'openInterest': int(float(l[7]))
        }
        return d

    # ----------------------------------------------------------------------
    def getHisBar(self, symbol,num,stdt='',eddt='',period=''):
        """获取历史K线数据"""
        path = 'hisminbar'

        # 默认参数
        params = {
            'id': symbol,
            'num': num
        }
        # 可选参数
        if stdt:
            params['stdt'] = stdt
        if eddt:
            params['eddt'] = eddt
        if period:
            params['period']=period

        data = self.getData(path, params)
        if not data:
            return None

        barList = []
        l = data.split(';')

        for barStr in l:
            # 过滤某些空数据
            if ',' not in barStr:
                continue

            barData = barStr.split(',')
            # d = {
            #     'symbol': barData[0],
            #     # 'date': barData[1],   # trading day
            #     'time': barData[2],
            #     'open': float(barData[3]),
            #     'high': float(barData[4]),
            #     'low': float(barData[5]),
            #     'close': float(barData[6]),
            #     'volume': int(barData[7]),
            #     'openInterest': int(float(barData[8])),
            #     'date': barData[9]  # natural day
            # }
            d = {
                'OpenInterest': int(float(barData[8])),
                'Close': float(barData[6]),
                'DateTime':'{0}-{1}-{2} {3}:{4}:00'.format(barData[9][0:4],barData[9][4:6],barData[9][6:8],barData[2][:2],barData[2][2:]),  # natural day
                'Low': float(barData[5]),
                'High': float(barData[4]),
                'Open': float(barData[3]),
                'Volume': int(barData[7]),
                'Tradingday':barData[1],
                'Instrument':symbol
            }
            if d['Low']>0 and d['Close']>0 and d['High']>0: #防止一些全部是0的数据
                barList.append(d)
        barList.reverse()
        return barList




SHCIFCO_IP = "180.169.126.123"
SHCIFCO_PORT  = "10083"
SHCIFCO_TOKEN = "jhr56d23c43c9e1620b66530f2f835c36a82fd"
api = ShcifcoApi(SHCIFCO_IP, SHCIFCO_PORT, SHCIFCO_TOKEN)       # 历史行情服务API对象

def downMinuteBarBySymbol(symbol, num=1,stdt='',eddt='',period=PERIOD_1MIN)->[]:
    """
    下载某一合约的分钟线数据"
    :param symbol:
    :param num:1m/3m/5m/10m/15m 3分钟、5分钟、10分钟、15分钟的拟合K线 None为1分
    :param stdt: 起始交易日   是交易日 不是日期
    :param eddt: 结束交易日   不是日期
    :return:
    """
    start = time.time()
    l = api.getHisBar(symbol, num, stdt,eddt,period)
    if not l:
        print
        u'%s数据下载失败' % symbol
        return

    # for d in l:
    #     bar = generateVtBar(d)
    #     d = bar.__dict__
    #     flt = {'datetime': bar.datetime}

    end = time.time()
    cost = (end - start) * 1000


    print ('合约%s数据下载完成%s - %s，耗时%s毫秒' % (symbol, l[0]['DateTime'],
                                   l[-1]['DateTime'], cost))
    return l
def read_from_zq(stra) -> []:
    """
    :param stra:策略
    :return: 返回加载的数据
    """
    #中期
    # {'OpenInterest': 110256, 'Close': 3596.0, 'DateTime': '2018-07-12 21:00:00', 'Low': 3574.0, 'High': 3598.0, 'Open': 3574.0,
    # 'Volume': 6664, 'TradingDay': '20180713', 'Instrument': 'rb1905'}
   #海风
    # {'Instrument': 'rb1905', 'Tradingday': '20180525', 'High': 3388.0, 'Low': 3378.0, 'Open': 3388.0, 'Close': 3381.0,
    #  'Volume': 78, 'OpenInterest': 28638.0, 'DateTime': '2018-05-24 21:00:00'}

    bars =[]
    for data in stra.Datas:
        #bars.extend(downMinuteBarBySymbol(data.Instrument, stdt=stra.BeginDate, eddt=stra.EndDate,period=PERIOD_15MIN)) # 测试的时候用这个 速度快 周期长 实盘还是使用普通的吧
        bars.extend(downMinuteBarBySymbol(data.Instrument,stdt=stra.BeginDate,eddt=stra.EndDate))

    bars.sort(key=lambda bar: bar['DateTime'])  # 按时间升序
    return bars

    # return downMinuteBarBySymbol(stra.Instrument,stdt=stra.BeginDate,eddt=stra.EndDate)
if __name__=="__main__":
    print(downMinuteBarBySymbol('rb1905',stdt='20180611',eddt='20190124',period='5m'))
